#define _CRT_SECURE_NO_WARNINGS 1

#include "Stack.h"

void STInit(ST* ps)
{
	ps->arr = NULL;
	ps->top = ps->capacity = 0;
}

void STDestroy(ST* ps)
{
	if (ps->arr)
	{
		free(ps->arr);
		ps->arr = NULL;
	}
	ps->capacity = ps->top = 0;
}

void StackPush(ST* ps, STDataType x)
{
	assert(ps);
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		STDataType* temp = (STDataType*)realloc(ps->arr, newcapacity * sizeof(STDataType));
		if (temp == NULL)
		{
			perror("realloc fail!");
			exit(1);
		}
		ps->arr = temp;
		ps->capacity = newcapacity;
	}
	ps->arr[ps->top++] = x;
}

void STPrint(ST* ps)
{
	assert(ps);
	for (int i = ps->top - 1; i >= 0; i--)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\r\n");
}

bool STEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}

void StackPop(ST* ps)
{
	assert(!STEmpty(ps));
	ps->top--;
}

STDataType StackTop(ST* ps)
{
	assert(!STEmpty(ps));
	return ps->arr[ps->top - 1];
}

int STSize(ST* ps)
{
	assert(ps);
	return ps->top;
}